<template>
  <el-dialog destroy-on-close v-model="dialogVisible" width="580px" class="ui-dialog-unheader chat-selection-wrap"
    :before-close="resetForm">
    <div class="display-flex create-group-chat">
      <div class="left">
        <div class="from-search">
          <el-input ref="pkgId" v-model="input" prefix-icon="el-icon-search" :placeholder="$t('search')" clearable
            class="from-search-input" @change="searchBtn" />
          <img class="from-search-search" src="@/assets/images/icon-search.png" alt="" />
        </div>
        <!--   // 0：创建群聊
    // 1: 添加群员
    // 2: 转发最近联系人
    // 3: 转发新聊天
    // 4：添加管理员 (在原有上面添加) -->
        <p class="title" v-if="setTypeCode == 4">群成员列表</p>
        <!-- <div class="ui-friends-item-warp-box">
          <friendsList ref="friendsList" :type="1" @friendProfileShow="friendProfileShow" checkedItem="1"
            @checkedData="checkedData" :checkListFill="checkListFill" :setType="setTypeCode"></friendsList>
        </div> -->
        <!-- 
          checkedItem
          //0:带右键菜单
    //1: 带checked 选中框
    //2: 带删除框
    //3:不按字母排序的 -->
        <el-scrollbar>
          <friendsList ref="friendsList" :type="2" @friendProfileShow="friendProfileShow" checkedItem="1"
            @checkedData="checkedData" :gMemberList="gMemberList" :checkedDefaultList="checkedDefaultList"
            :setType="setTypeCode">
          </friendsList>
        </el-scrollbar>
      </div>
      <div class="right">
        <p class="title">{{ title }}</p>
        <div class="checked-list" :class="{ 'max-h-392': setTypeCode === 4 }">
          <friendsList ref="friendsList2" v-if="checkedItemRight == 2" :type="2" @friendProfileShow="friendProfileShow"
            :checkedItem="checkedItemRight" :checkedPropsList="checkedList"
            @updateGroupMemberList="updateGroupMemberList"></friendsList>
        </div>
        <el-form class="ui-form" label-position="top" label-width="100px" :model="formLabelAlign"
          style="max-width: 460px" @keyup.enter="submitForm()" @submit.native.prevent>
          <el-form-item class="text-right ui-btn-group">
            <el-button type="info" plain @click="resetForm()">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="submitForm()" :loading="loading" :disabled="confirmDisable">
              {{ $t("confirm") }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-dialog>
  <dialog-conter-view ref="dialogConterView" :cancelShow="false">
    <template v-slot:content>
      <p v-if="con == 0">{{ $t("groupNameRequired") }}</p>
      <p v-if="con == 1">{{ $t("notSelectedMember") }}</p>
    </template>
  </dialog-conter-view>

  
</template>

<script>
// import dialogConterView from '@/components/dialog/dialogConterView.vue'
import friendsList from '@/components/form/friendsItem2.vue'
import { mapGetters, mapState } from "vuex";
import {
  ADD_GROUP_MANAGER, PANEL_HEADER_LIST_VISIBLE, PANEL_HEADER_LIST_VISIBLE_CLOSE,
  BATCH_ADD_MANAGER,
  LIMIT_SELECT_MAX,
  UPDATE_G_MEMBER_LIST,
} from "@/store/actiontypes";

export default {
  name: "CreateGroupChat2",
  components: {
    friendsList,
    dialogView,
    // dialogConterView
  },
  props: {
    title: {
      type: String,
      dafault: () => this.$t("createGroupChat"),
    },
    // 0：创建群聊
    // 1: 添加群员
    // 2: 转发最近联系人
    // 3: 转发新聊天
    // 4：添加管理员 (在原有上面添加)
    setType: {
      type: Number,
      dafault: 0
    },
    obj: {
      type: Object,
      dafault: {
        targetId: ''
      }
    },
    //消息信息
    msgObj: {
      type: Object,
      default: {

      }
    },
    msgType: {
      type: String,
      dafault: ''
    },
    // 
    talkPanelData: {
      type: Object,
      default: function () {
        return {};
      },
    },
    maxlength: {
      type: Number,
      default: 1000,
    }
  },
  data() {
    return {
      maxGroup: 7, //群人数上限
      loading: false,
      con: 0,
      checkedList: [],
      checkedItemRight: -1, //为2才显示右边  默认为-1
      dialogVisible: false,
      dialogConterVisible: false,
      input: '',
      talkItemsA: '',
      formLabelAlign: {
        name: '',
        region: '',
        type: '',
      },
      setTypeCode: this.setType,//setType=4 
      talkPanelObjData: JSON.parse(window.localStorage.talkPanelObj ?? '[]'),
      msgCode: 0,
      activeItem: {},
      seletedListLength: [], // 群聊添加成员时，初始已选成员
      confirmDisable: true,
    }
  },
  computed: {
    ...mapState({
      sessionList: (state) => state.chat.sessionList,
      gMemberList: (state) => {
        return state.chat.gMemberList
      },
      checkedDefaultList: (state) => {
        return state.chat.checkedDefaultList
      }
    }),
    friendsInGroupsLength() {
      let len = 0;
      this.groupMemberList.forEach(item => {
        if (item.isManager) {
          len++
        }
      });
      return len;
    }
  },
  methods: {
    // 查询
    searchBtn() {
      this.$refs.friendsList.search(this.input.toUpperCase())
    },
    friendProfileShow() {

    },
    //
    setData(data, topField, dateField) {
      var topData = [], defaultData = []
      data.forEach(element => {
        if (element[topField] == 1) {
          topData.push(element)
        } else {
          defaultData.push(element)
        }
      });
      topData = topData.sort(this.compare(dateField, 'positive'))
      defaultData = defaultData.sort(this.compare(dateField, 'positive'))
      return {
        data: topData.concat(defaultData),
        topData: topData,
        defaultData: defaultData
      }
    },
    /**
     * 第一次的时候 子组件回调函数
     * @param {} v 
     */
    checkedData({ list, checkedItem }) {
      // {
      //     list: [],
      //     checkedItem: 2,
      //   }

      this.gMemberList.forEach((item) => {
        if (item.userId === checkedItem.userId) {
          item.isManager = true
        }
      })
      this.checkedList = list
      this.checkedItemRight = 2
      this.confirmDisable = false
    },
    //右边子组件会回调父组件方法
    updateGroupMemberList({ delItem,confirmDisable }) {
      const newGroupMemberList = JSON.parse(JSON.stringify(this.gMemberList))
      console.log("修改前", JSON.stringify(newGroupMemberList))
      newGroupMemberList.forEach((item) => {
        if (item.userId === delItem.userId) {
          console.log("修改前", JSON.stringify(item), item.isManager)
          //改变为非管理员
          item.isManager = false
          console.log("修改后", JSON.stringify(item))
        }
      })
      this.confirmDisable = confirmDisable
      this.$store.commit(UPDATE_G_MEMBER_LIST, {
        gMemberList: newGroupMemberList
      })
    },
    resetForm(formEl) {
      //重置上一个弹窗 重置state内存变量
      this.$store.commit(PANEL_HEADER_LIST_VISIBLE, {
        panelHeaderListSelectVisible: PANEL_HEADER_LIST_VISIBLE_CLOSE
      })
      this.loading = false;
      this.checkedList = []
      this.dialogVisible = false
      this.input = '';
      this.formLabelAlign.name = ''
      this.checkedList = []

      // if (!formEl) return
      // formEl.resetFields()
    },
    setTypeChange() {

    },
    //修改管理员
    submitForm(v) {

      console.log('submitForm-------------------------setTypeCode:', this.setTypeCode, '-------------------------setType:', this.setType);
      this.loading = true
      //重置上一个
      this.$store.commit(LIMIT_SELECT_MAX, {
        limitMax: 0
      })
      let userIdList = []
      this.$refs.friendsList.checkedManagerList.forEach((item) => {
        userIdList.push(item.userId)
      })
      this.$store.commit(PANEL_HEADER_LIST_VISIBLE, {
        panelHeaderListSelectVisible: PANEL_HEADER_LIST_VISIBLE_CLOSE
      })
      //const s = JSON.parse(JSON.stringify(this.$store.state.chat.currentSession))
      //const s2 = JSON.parse(JSON.stringify(this.$store.state.chat.currentGroupInfo))

      this.$store.dispatch(BATCH_ADD_MANAGER, {
        userIdList,
        groupId: this.$store.state.chat.currentSession.targetId
      }).then((res) => {
        console.log('入群管理成功', res)
        this.$refs.friendsList.checkedManagerList = []
        this.checkedList = []
        this.dialogVisible = false
        //群ID 
        this.loading = false
      })

    },
    //创建新聊天
    createNewChat() {
      this.checkedList = []
      const that = this
      that.$nextTick(() => {
        that.setTypeCode = 3
        that.$refs.friendsList.search('')
      })
    },
    // 
    logoutDialogClose() {

    },
    // 
    logoutDialogOk() {
      const than = this
      if (this.msgCode == 0) {
        // toChat('GROUP', than.activeItem.groupId);
      }
    }
  },
  watch: {
    sessionList: {
      handler(v) {
        var con = 0;
        var conA = '';
        var than = this;
        // than.sessionList.forEach((fv,fi,farr)=>{
        //     if(!fv.isTop){
        //       con++
        //     }
        //     if(con==1){
        //       conA=fv
        //       than.$parent.clickTab(fv.targetId, fv)
        //     }
        // })
      },
      deep: true,
      immediate: true

    },
    input() {
      this.$refs.friendsList.search(this.input)
    },
    dialogVisible: {
      handler(v) {
        if (v) {
          // this.$refs.pkgId.focus()
          this.$nextTick(() => {
            this.$refs.pkgId.focus()
            this.setTypeChange();
            // if(v){

            // }
            //this.$refs.friendsList.
          })
        }
      }
    }
  }
};
</script>

<style scoped lang="less">
.create-group-chat {

  .left,
  .right {
    padding: 16px 0;
  }

  .left {
    width: 236px;
    border-right: 1px solid #EEEEEE;

    .from-search {
      margin: 0 20px;
    }

    .title {
      padding: 10px 20px 8px;
      border-bottom: 1px solid #F3F3F3;
      font-size: 12px;
      font-weight: 500;
      color: #303133;
    }
  }

  .right {
    flex: 1;

    .title {
      margin-bottom: 10px;
      padding: 0 20px;
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      line-height: 16px;
    }

    .checked-list {
      height: 300px;
      overflow: auto;
    }

    .max-h-392 {
      height: auto;
      max-height: 392px;
    }

    .ui-form {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 20px;
      padding-top: 10px;
      margin: 0 20px;
      /*border-top: 1px solid #EEEEEE;*/
    }

  }

}
</style>
<style lang="less">
.ui-dialog-unheader {
  .el-dialog__headerbtn {
    top: 16px;
    right: 0;
    padding: 0;
    width: auto;
    height: auto;
  }

  // .ui-friends-item-warp-box {
  //   height: 400px;
  //   overflow: auto;
  // }
  .el-scrollbar {
    height: 400px;
    overflow: auto;
  }

  .right {
    position: relative;

    .ui-btn-group {

      /*margin: 0 20px;*/
      .el-form-item__content {
        display: block !important;

        .el-button {
          width: 88px;
          height: 26px;
          line-height: 26px;

          span {
            font-size: 14px;
            font-weight: 400;
            color: #303133;
          }
        }
      }
    }

    /*.ui-form{*/
    /*padding-top: 10px;*/
    /*position: absolute;*/
    /*bottom: 38px;*/
    /*left: 0;*/
    /*right: 0;*/
    /*margin: 0 20px;*/
    /*border-top: 1px solid #EEEEEE;*/
    /*}*/
  }

}

.chat-selection-wrap {
  .el-dialog__header {
    opacity: inherit !important;
  }
}
</style>